package org.esjsoftware.v2m.rim.proxy;

import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import org.esjsoftware.v2m.rim.util.Base64;

/**
 * 
 * @author Ernest
 *
 */
public class MessageProxy{
	public String sendMessage(String username, String password, String sourcePhoneNumber, String destinationPhoneNumber, byte[] audioMessageData, String scheduleDatetimeString){
		String result = "";
		HttpConnection http = null; 
		InputStream is = null; 
		OutputStream os = null;
		try{
			http =(HttpConnection)Connector.open("http://vsp.pbxsms.com/api.php"); 
			http.setRequestMethod(HttpConnection.POST); 
			http.setRequestProperty("User-Agent", "Voice2Mobiles"); 
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
			os = http.openOutputStream(); 
			String params = "http=1&username=" + username + "&password=" + password + "&cmd=sendsms&source=" + sourcePhoneNumber + "&destination=" + destinationPhoneNumber + "&audio=" + Base64.encode(audioMessageData) + "&scheduleTimestamp=" + scheduleDatetimeString; 
			os.write(params.getBytes()); 
			os.flush(); 
			
			StringBuffer messageSend = new StringBuffer(); 
			is = http.openDataInputStream(); 
			int chr; 
			while((chr = is.read()) != -1) { 
				messageSend.append((char) chr); 
			} 
			result = messageSend.toString();
		} catch (Exception e) {
			return "Error sending message: unable to access the internet. Please check your connection";
		} finally {
			try {
				if(is != null) 
					is.close(); 
				if(os != null) 
					os.close(); 
				if(http != null) 
					http.close();
			} catch (Exception e) {
				
			}
		}
		
		return result;
	}
	
	public String getMessageStatus(String username, String password, String sourcePhoneNumber){
		String result = "";
		HttpConnection http = null; 
		InputStream is = null; 
		OutputStream os = null;
		try {
			http =(HttpConnection)Connector.open("http://vsp.pbxsms.com/api.php"); 
			http.setRequestMethod(HttpConnection.POST); 
			http.setRequestProperty("User-Agent", "Voice2Mobiles"); 
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
			os = http.openOutputStream(); 
			String params = "http=1&username=" + username + "&password=" + password + "&cmd=getstatus&source=" + sourcePhoneNumber; 
			os.write(params.getBytes()); 
			os.flush(); 
			
			StringBuffer messageSend = new StringBuffer(); 
			is = http.openDataInputStream(); 
			int chr; 
			while((chr = is.read()) != -1) { 
				messageSend.append((char) chr); 
			} 
			result = messageSend.toString();
		} catch (Exception e) {
			return "Todo: Errors!!";
		} finally {
			try {
				if(is != null) 
					is.close(); 
				if(os != null) 
					os.close(); 
				if(http != null) 
					http.close();
			} catch (Exception e) {
				
			}
		}
		
		return result;
	}
}
